package cn.anc.aonicardv.module.adpter.recorder;


import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.anc.aonicardv.GlideApp;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.AllSelectEvent;
import cn.anc.aonicardv.event.EditEvent;
import cn.anc.aonicardv.event.SelectEvent;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.ui.recorder.RecorderUrgentFragment;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/19.
 */

public class RecorderUrgentAdapter extends RecyclerView.Adapter {

    private List<VideoBean> videoBeanList = new ArrayList<>();
    private boolean isEditMode;
    private RecorderUrgentFragment fragment;
    private int mItemMargin;
    private int mRecorderWidth,mRecorderItemWidth;
    private int rowNumber;
    public RecorderUrgentAdapter(List<VideoBean> videoBeanList, RecorderUrgentFragment fragment,int mRowNumber) {
        this.videoBeanList = videoBeanList;
        this.fragment = fragment;
        this.rowNumber = mRowNumber;
        int left = fragment.getResources().getDimensionPixelSize(R.dimen.dp_15);
        int right = fragment.getResources().getDimensionPixelSize(R.dimen.dp_220);
        mRecorderWidth = fragment.getResources().getDisplayMetrics().widthPixels   -left- right;
        mItemMargin = fragment.getResources().getDimensionPixelSize(R.dimen.dp_20);
        mRecorderItemWidth = (mRecorderWidth-rowNumber*mItemMargin)/rowNumber;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_video, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
        layoutParams.width = mRecorderItemWidth;
        layoutParams.height = mRecorderItemWidth * 9 / 16;
        layoutParams.leftMargin = mItemMargin;
        layoutParams.bottomMargin = mItemMargin;
        CarControl.CarDvThumbnailMediaInfo mediaInfo = CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(videoBeanList.get(position).getPath()));
        if (mediaInfo != null) {
            String resolution = mediaInfo.resolution;
            String fileCreateTime = mediaInfo.file_time;
            if (resolution != null) {
                String sub_res = resolution.substring(resolution.lastIndexOf("x") + 1, resolution.length()) + "P";
                viewHolder.resolutionTv.setVisibility(View.VISIBLE);
                viewHolder.resolutionTv.setText(sub_res);
            } else
                viewHolder.resolutionTv.setVisibility(View.GONE);
            if (fileCreateTime != null) {
                viewHolder.timeTv.setVisibility(View.GONE);
                viewHolder.timeTv.setText(fileCreateTime);
            } else
                viewHolder.timeTv.setVisibility(View.GONE);
        } else {
            viewHolder.resolutionTv.setVisibility(View.GONE);
            viewHolder.timeTv.setVisibility(View.GONE);
        }
        viewHolder.selectCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (viewHolder.selectCb.isPressed()) {
                    videoBeanList.get(position).setCheck(isChecked);
                    EventBus.getDefault().post(new SelectEvent(isChecked, videoBeanList.size()));
                }
            }
        });
        if (videoBeanList.get(position).isCheck()) {
            viewHolder.selectCb.setChecked(true);
            viewHolder.mask.setVisibility(View.VISIBLE);
        } else {
            viewHolder.selectCb.setChecked(false);
            viewHolder.mask.setVisibility(View.GONE);
        }
        if (isEditMode) {
            viewHolder.selectCb.setVisibility(View.VISIBLE);
        } else {
            viewHolder.selectCb.setChecked(false);
            viewHolder.selectCb.setVisibility(View.GONE);
        }
        viewHolder.videoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditMode) {
                    if (viewHolder.mask.getVisibility() == View.GONE)
                        viewHolder.mask.setVisibility(View.VISIBLE);
                    else
                        viewHolder.mask.setVisibility(View.GONE);
                }
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(viewHolder.selectCb, position, isEditMode);
                }
            }
        });
        viewHolder.videoIv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (onItemLongClickListener != null)
                    onItemLongClickListener.onItemLongClick(v, position, isEditMode);
                return true;
            }
        });
        String cache_path = CacheManager.getCachePath(videoBeanList.get(position).getPath());
        File file = new File(cache_path);
        if (file.exists()) {
            videoBeanList.get(position).setLoadStatus(true);
            GlideApp.with(fragment.getContext()).load(file).placeholder(R.mipmap.image_loading).into(viewHolder.videoIv);
        } else {
            videoBeanList.get(position).setLoadStatus(false);
            viewHolder.videoIv.setImageResource(R.mipmap.image_loading);
        }

    }

    /**
     * 刷新适配器数据列表
     *
     * @param dataList 待添加的数据列表
     */
    public void refreshDataList( List<VideoBean> dataList) {
        if (dataList != null&&dataList.size()>0) {
            videoBeanList.clear();
            videoBeanList.addAll(dataList);
            notifyDataSetChanged();
        }
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EditEvent event) {
        if (!fragment.getUserVisibleHint())
            return;
        this.isEditMode = event.isEdit;
        for (VideoBean p : videoBeanList) {
            p.setCheck(false);
        }
        notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AllSelectEvent event) {
        if (videoBeanList == null || !fragment.getUserVisibleHint()) {
            return;
        }
        for (VideoBean p : videoBeanList) {
            p.setCheck(event.isAllSelect);
        }
        notifyDataSetChanged();
    }


    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public int getItemCount() {
        return videoBeanList == null ? 0 : videoBeanList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView videoIv;
        public TextView resolutionTv;
        public TextView timeTv;
        public CheckBox selectCb;
        public View mask;

        public ViewHolder(View view) {
            super(view);
            videoIv = (ImageView) view.findViewById(R.id.iv_video);
            resolutionTv = (TextView) view.findViewById(R.id.tv_resolution);
            timeTv = (TextView) view.findViewById(R.id.tv_time);
            selectCb = (CheckBox) view.findViewById(R.id.cb_select);

            mask = view.findViewById(R.id.mask);
        }
    }

    private OnAlbumItemClickListener onItemClickListener;

    private OnAlbumItemLongClickListener onItemLongClickListener;

    public void setOnItemClickListener(OnAlbumItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemLongClickListener(OnAlbumItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }

    public void registerEventBusForAdapter(){
        EventBus.getDefault().register(this);
    }

    public void unregisterEventBusForAdapter(){
        EventBus.getDefault().unregister(this);
    }
}
